package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
@Slf4j
//过滤器
public class LoginCheckFilter implements Filter {

    //路径匹配器，支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //转Http请求
        HttpServletRequest requ = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;

        //获取本次请求的URI
        String requestURI = requ.getRequestURI();
        //记录日志拦截到的请求
        log.info("拦截到的请求:{}",requestURI);
        //定义不要处理的请求
        String[] nourls=new String[]{
          "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/user/sendMsg",
                "/user/login"
        };
        //判断本次请求是否需要处理
        boolean check=check(nourls,requestURI);
        //如果不需要处理，则直接放行
        if (check){
            //记录不需要处理的日志
            log.info("本次请求{}不需要处理",requestURI);
            //然后放行
            filterChain.doFilter(requ,resp);
            //放行跳出
            return;
        }
        //判断登录状态，如果已登录，则直接放行,后台
        if (requ.getSession().getAttribute("employee")!=null){
            //记录用户登录的日志
            log.info("用户名已登录,用户ip为:{}",requ.getSession().getAttribute("employee"));
            //设置当前线程的用户id
            Long empId=(Long)requ.getSession().getAttribute("employee");
            BaseContext.setCurrentId(empId);
            //放行
            filterChain.doFilter(requ,resp);
            return;
        }

        //判断登录状态，如果已登录，则直接放行,前台
        if (requ.getSession().getAttribute("user")!=null){
            //记录用户登录的日志
            log.info("用户名已登录,用户ip为:{}",requ.getSession().getAttribute("user"));
            //设置当前线程的用户id
            Long userId=(Long)requ.getSession().getAttribute("user");
            BaseContext.setCurrentId(userId);
            //放行
            filterChain.doFilter(requ,resp);
            return;
        }
        log.info("用户未登录");
        //如果未登录则返回未登录结果，通过输出流方式向客户端页面响应数据
        resp.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }
    //检查本次请求是否需要放行
    private boolean check(String[] nourls, String requestURI) {
        for (String nourl : nourls) {
            boolean match = PATH_MATCHER.match(nourl, requestURI);
            if (match){
                return true;
            }
        }
        return false;
    }
}
